﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;

namespace Xceed.Silverlight.Data
{
  internal abstract class PagingEnumerator<T> : AsyncParentEnumerator<T>
  {
    #region Constructors

    protected PagingEnumerator( IAsyncEnumerator childEnumerator )
      : base( childEnumerator )
    {
    }

    protected PagingEnumerator( IAsyncEnumerator childEnumerator, Func<int> pageSize )
      : this( childEnumerator )
    {
      m_pageSize = pageSize;
    }

    #endregion

    protected int GetFetchCount( long expectedFetchCount )
    {
      // There is nothing to fetch.
      if( expectedFetchCount == 0 )
        return 0;

      int pageSize = ( m_pageSize != null )
                       ? m_pageSize.Invoke()
                       : 0;

      // There is no page limit.
      if( pageSize <= 0 )
        return ( expectedFetchCount >= 0 )
                 ? ( int )Math.Min( expectedFetchCount, int.MaxValue )
                 : ( int )Math.Max( expectedFetchCount, int.MinValue );

      // Return a value that won't exceed the allowed page size.
      int fetchSize = ( int )Math.Min( Math.Abs( expectedFetchCount ), pageSize );
      return fetchSize * DataUtils.GetUnit( expectedFetchCount );
    }

    #region Private Fields

    private readonly Func<int> m_pageSize; //null

    #endregion
  }
}
